package com.example.ioc.context;

import com.example.common.Statistical;
import com.example.common.utils.Statistics;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/**
 * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory#addBeanPostProcessor(BeanPostProcessor)}
 * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(ConfigurableListableBeanFactory)}
 */
@Slf4j
//@Component //可以用Component注入
public final class LBeanPostProcessor implements BeanPostProcessor {

    private static volatile LBeanPostProcessor instance;

    private LBeanPostProcessor(){
        Statistics.logInfo(log);
    }

    public static LBeanPostProcessor getInstance(){
        if(instance == null){
            synchronized (LBeanPostProcessor.class){
                if(instance == null){
                    instance = new LBeanPostProcessor();
                }
            }
        }
        return instance;
    }

    @Override
    public Object postProcessBeforeInitialization(@NonNull final Object bean, @NonNull final String beanName) throws BeansException {
        if(bean instanceof Statistical statistical){
            Statistics.logInfo(log, statistical, "postProcessBeforeInitialization", bean);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(@NonNull final Object bean, @NonNull final String beanName) throws BeansException {
        if (bean instanceof Statistical statistical) {
            Statistics.logInfo(log, statistical, "postProcessAfterInitialization", bean);
        }
        return bean;
    }
}
